package com.thread.chapter3;

import cn.hutool.core.thread.ThreadUtil;
import lombok.Data;

@Data
public class Demo3_1_11 {

    private static String value = "";

    static class P {
        private String lock;

        public P(String lock) {
            this.lock = lock;
        }

        public void setValue() {
            try {
                synchronized (lock) {
                    if (!value.equals("")) {
                        lock.wait();
                    }
                    String v = System.currentTimeMillis() + "_" + System.nanoTime();
                    System.out.println("设置值:" + v);
                    value = v;
                    ThreadUtil.sleep(1000);
                    lock.notify();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    static class C {
        private String lock;

        public C(String lock) {
            this.lock = lock;
        }

        public void getValue() {
            try {
                synchronized (lock) {
                    if (value.equals("")) {
                        lock.wait();
                    }
                    System.out.println("获取值:" + value);
                    value = "";
                    lock.notify();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) {
        //一个生产者和一个消费者模式实现
        String lock = "";
        P p = new P(lock);
        C c = new C(lock);
        Thread pThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    p.setValue();
                }
            }
        });
        Thread cThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    c.getValue();
                }
            }
        });
        pThread.start();
        cThread.start();
    }
}
